package com.huali.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class BaseDao {
    private static DataSource dataSource = null;

    static {
        try {
            Properties properties = new Properties();
            properties.load(BaseDao.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static int executeUpdate(String sql,Object... data){
        Connection conn = null;
        PreparedStatement ps = null;
        int res = 0;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < data.length ;i++){
                ps.setObject(i + 1, data[i]);
            }
            res = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(conn,ps,null);
        }
        return res;
    }

    public static List<Map<String, Object>> executeQuery(String sql, Object... data) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList<>();
        try {
                 conn = getConnection();
                 ps = conn.prepareStatement(sql);
            for (int i = 0; i < data.length; i++) {
                ps.setObject(i + 1,data[i]);
            }
            rs = ps.executeQuery();
            int count = rs.getMetaData().getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= count; i++) {
                    String name = rs.getMetaData().getColumnLabel(i);
                    Object values = rs.getObject(i);
                    map.put(name, values);
                }
                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(conn, ps, rs);
        }
        return list;

    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }





}
